package com.htbb.common.http;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;  
import java.util.Map.Entry;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;  
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;  
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;



/* 
 * 利用HttpClient进行post请求的工具类 
 */  
public class HttpClientUtil {  
	
	private static final Logger logger = Logger.getLogger(HttpClientUtil.class);
	
	static{
		try {
			System.setProperty("jsse.enableSNIExtension", "false");
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	/**
	 * 发送post请求
	 * @param url 请求路径
	 * @param param 请求json数据
	 * @return
	 */
    public static String doPost(String url,JSONObject param){  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
        	HttpClient client =  new SSLClient();
            httpPost = new HttpPost(url); 
            if(param != null){
            	StringEntity se = new StringEntity(param.toString(),"utf-8"); 
//                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset="));
                httpPost.setEntity(se); //post方法中，加入json数据
                httpPost.setHeader("Content-Type","application/json");
            }
            
            HttpResponse response = client.execute(httpPost);
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"utf-8");  
                }  
            }  
            
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        System.out.println("返回结果:\n"+result);
        return result;  
    }  
    
    /**
	 * 发送post请求
	 * @param url 请求路径
	 * @param param 请求字符串数据
	 * @return
	 */
    public static String doPost(String url,String param){  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
        	HttpClient client =  new SSLClient();
            httpPost = new HttpPost(url); 
            if(param != null){
            	StringEntity se = new StringEntity(param.toString(),"utf-8"); 
//                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset="));
                httpPost.setEntity(se); //post方法中，加入json数据
                httpPost.setHeader("Content-Type","application/json");
            }
            
            HttpResponse response = client.execute(httpPost);
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"utf-8");  
                }  
            }  
            
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        System.out.println("返回结果:\n"+result);
        return result;  
    }  
    
    
    /**
	 * 发送post请求
	 * @param url 请求路径
	 * @param param 请求参数数据
	 * @return
	 */
    @SuppressWarnings("unchecked")
	public static String doPostMap(String url,Map<String, String> map){ 
    	
    	HttpClient httpClient = null;  
        HttpPost httpPost = null;  
        String result = null;  
        try{  
        	httpClient = new SSLClient();  
            httpPost = new HttpPost(url);  
            //设置参数  
            List<NameValuePair> list = new ArrayList<NameValuePair>();  
            Iterator iterator = map.entrySet().iterator();  
            while(iterator.hasNext()){  
                Entry<String,String> elem = (Entry<String, String>) iterator.next();  
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
            }  
            if(list.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");  
                httpPost.setEntity(entity);  
            }  
            HttpResponse response = httpClient.execute(httpPost);  
            if(response != null){  
                HttpEntity resEntity = response.getEntity();  
                if(resEntity != null){  
                    result = EntityUtils.toString(resEntity,"UTF-8");  
                }  
            }  
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        System.out.println("返回结果:\n"+result);
        return result;  
    }  
    
    /**
     * 发送get请求
     * @param url 请求路径
     * @param param 请求json数据
     * @return
     */
    public static String doGet(String url){
    	 String result = null;  
    	 try{  
    		HttpClient client = new SSLClient();
    		//用get方法发送http请求
	        HttpGet get = new HttpGet(url);
	        CloseableHttpResponse httpResponse = null;
	        //发送get请求
	        httpResponse = (CloseableHttpResponse) client.execute(get);
	        try{
	            //response实体
	            HttpEntity entity = httpResponse.getEntity();
	            if (null != entity){
	                result = EntityUtils.toString(entity,"utf-8"); 
	            }
	        }
	        finally{
	            httpResponse.close();
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;  
	}  
    
    public static void main(String[] args) {
//    	String url="www.daily.zhongan.com/open/common/downloadFileScreen/downloadPolicyVoucher.do?data=2780320ee926531c163af37a2b161c0b8fd5b72153af7feb";
//    	String res = doPost(url, "");
//    	System.out.println(res);
    	String notifyUrl= "https://pre.m.qubao100.com/callback/insurance/haitun/payment.sgi?payNo=1499064242473949&hbCode=1499064242356767";
    	System.out.println("请求第三方url："+notifyUrl);
		String result = HttpClientUtil.doGet(notifyUrl);
		System.out.println("第三方响应内容："+result);
		String isSuccess = "0";//0表示成功，1表示失败
		if(!"SUCCESS".equalsIgnoreCase(result)){
			logger.info("请求第三方url："+notifyUrl+"  失败");
			isSuccess = "1";
		}
		System.out.println(isSuccess);
	}
    
    
    /**
   	 * 发送post请求
   	 * @param url 请求路径
   	 * @param param 请求字符串数据
   	 * @return
   	 */
       public static String doPostForInterface(String url,String param,String partnerCode){  
           HttpPost httpPost = null;  
           String result = null;  
           try{  
           	HttpClient client =  new SSLClient();
               httpPost = new HttpPost(url); 
               if(param != null){
               	StringEntity se = new StringEntity(param.toString(),"utf-8"); 
                   httpPost.setEntity(se); //post方法中，加入json数据
                   httpPost.setHeader("Content-Type","application/json");
                   httpPost.setHeader("partnerCode",partnerCode);
               }
               
               HttpResponse response = client.execute(httpPost);
               if(response != null){  
                   HttpEntity resEntity = response.getEntity();  
                   if(resEntity != null){  
                       result = EntityUtils.toString(resEntity,"utf-8");  
                   }  
               }  
               
           }catch(Exception ex){  
               ex.printStackTrace();  
           }  
           System.out.println("返回结果:\n"+result);
           return result;  
       }  
       
       
    
}  





